<template>
    <div class="permission-list-container">
        <!-- 顶部信息区域 -->
        <div class="header">
            <el-avatar :size="60" src="" class="avatar"></el-avatar>
            <div class="info">
                <div class="title">{{ RoleInfo.roleName }}</div>
                <div class="description">暂无相关描述</div>
            </div>
            <div class="actions">
                <el-button type="primary" @click="handleCreateRole">添加人员</el-button>
                <el-button @click="handleEditRole">编辑职务</el-button>
                <el-button @click="handleSetStatus">设置状态</el-button>
                <el-button @click="handleCreateRole">复制职务</el-button>
                <el-button type="danger" @click="handleDeleteRole">删除职务</el-button>
                                <el-button type="success" @click="ReturnRole">返回</el-button>
            </div>
        </div>

        <!-- 标签页导航 -->
        <el-tabs v-model="activeTab" class="permission-tabs">
            <el-tab-pane label="操作权限" name="operation">
                <el-table :data="PermissionList" style="width: 100%">
                    <el-table-column prop="permissionName">
                        <template #default="scope">
                            <el-checkbox v-model="PermissionArray" @click="SetPermissionId(scope.row)" :label="scope.row.permissionId" >
                                {{ scope.row.permissionName }}
                            </el-checkbox>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="数据权限" name="data">数据权限内容</el-tab-pane>
            <el-tab-pane label="字段权限" name="field">字段权限内容</el-tab-pane>
            <el-tab-pane label="成员列表" name="members">成员列表内容</el-tab-pane>
            <el-tab-pane label="操作记录" name="logs">操作记录内容</el-tab-pane>
        </el-tabs>
    </div>

    <!-- 新建职务模态框 -->
    <el-dialog title="新建职务" v-model="AddDialogVisible" width="30%">
        <!-- 模态框内容 -->
        <el-form :model="AddForm" :rules="AddRules" ref="AddFormRef" label-width="100px">
            <el-form-item label="职务名称:" prop="roleName">
                <el-input v-model="AddForm.roleName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="职务描述:" prop="departmentDescription" required>
                <el-input type="textarea" v-model="AddForm.departmentDescription" placeholder="请输入内容" maxlength="100"
                    show-word-limit :rows="4"></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="AddDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveAdd">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑职务模态框 -->
    <el-dialog title="编辑职务" v-model="updateDialogVisible" width="30%">
        <!-- 模态框内容 -->
        <el-form :model="UpdateForm" :rules="UpdateRules" ref="updateFormRef" label-width="100px">
            <el-form-item label="职务名称:" prop="RoleName">
                <el-input v-model="UpdateForm.RoleName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="职务描述:" prop="DepartmentDescription" required>
                <el-input type="textarea" v-model="UpdateForm.DepartmentDescription" placeholder="请输入内容" maxlength="100"
                    show-word-limit :rows="4"></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="updateDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveupdate">保存</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 设置状态模态框 -->
    <el-dialog title="设置状态" v-model="statusDialogVisible" width="30%" @close="resetupdateDialog">
        <!-- 模态框内容 -->
        <el-form :model="statusForm" :rules="statusRules" ref="statusFormRef" label-width="100px">
            <el-form-item label="选择状态:" prop="RoleStatus" required>
                <el-radio-group v-model="statusForm.RoleStatus">
                    <el-radio-button :label="0">启用</el-radio-button>
                    <el-radio-button :label="1">禁用</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="备注内容:" prop="ContentDesc" required>
                <el-input type="textarea" v-model="statusForm.ContentDesc" placeholder="请输入内容" maxlength="100"
                    show-word-limit :rows="4"></el-input>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="statusDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveStatus">保存</el-button>
            </span>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { GetPermission ,SetPermission,GetPermissionByRoleId} from '@/Api/permission'
import { ElMessage, ElMessageBox } from 'element-plus';
import { DeleteRole, UpdateRoleStatus, UpdateRoleZhiW, AddRoleZhiW } from '@/Api/role';
import moment from 'moment';
import type { FormInstance, FormRules } from 'element-plus';
import router from '@/router';

const localroleinfo = <any>reactive({
    localroleid: localStorage.getItem('roleId'),
    localrolename: localStorage.getItem('roleName'),
    localstate: localStorage.getItem('roleStatus'),
    localdesc: localStorage.getItem('departmentDescription')
})

//存储权限数组
const PermissionArray = reactive<number[]>([])

const SetPermissionId=(row:any)=>{
if(!PermissionArray.includes(row.permissionId)){
PermissionArray.push(row.permissionId)
}
else{
    //PermissionArray.findIndex((x:any)=>x==row.permissionId)
    PermissionArray.splice(PermissionArray.indexOf(row.permissionId),1)

}
console.log(PermissionArray);
}





// 控制新建职务对话框的显示隐藏
const AddDialogVisible = ref(false);

// 控制编辑职务对话框的显示隐藏
const updateDialogVisible = ref(false);

// 控制设置状态对话框的显示隐藏
const statusDialogVisible = ref(false);


// 新建职务表单ref
const AddFormRef = ref<FormInstance>();

// 新建职务表单
const AddForm = reactive({
    roleName: '',
    departmentDescription: '',
});

// 新建职务表单校验
const AddRules = reactive<FormRules>({
    roleName: [{ required: true, message: '请输入职务名称', trigger: 'change' }],
    departmentDescription: [
        { required: true, message: '请输入职务描述', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});


// 编辑职务表单ref
const updateFormRef = ref<FormInstance>();

// 编辑职务表单
const UpdateForm = reactive({
    Roleid: '', // 角色ID
    RoleName: '',
    DepartmentDescription: '',
});

// 编辑职务表单校验
const UpdateRules = reactive<FormRules>({
    RoleName: [{ required: true, message: '请输入职务名称', trigger: 'change' }],
    DepartmentDescription: [
        { required: true, message: '请输入职务描述', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});

// 设置状态表单ref
const statusFormRef = ref<FormInstance>();

// 设置状态表单
const statusForm = reactive({
    RoleId: '', // 添加角色ID字段
    RoleStatus: 0, // 默认启用
    ContentDesc: '',
});

// 设置状态表单校验
const statusRules = reactive<FormRules>({
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    ContentDesc: [
        { required: true, message: '请输入备注内容', trigger: 'blur' },
        { max: 100, message: '备注内容不能超过100个字符', trigger: 'blur' },
    ],
});


// 处理新建职务
const handleCreateRole = () => {
    AddDialogVisible.value = true
    AddForm.roleName = '',
        AddForm.departmentDescription = ''
};

// 处理编辑职务
const handleEditRole = () => {
    updateDialogVisible.value = true
    UpdateForm.Roleid = localroleinfo.localroleid,
        UpdateForm.RoleName = localroleinfo.localrolename,
        UpdateForm.DepartmentDescription = localroleinfo.localdesc
    console.log(UpdateForm);
};

// 处理设置状态
const handleSetStatus = () => {
    // 填充表单数据
    statusForm.RoleId = localroleinfo.localroleid;
    statusForm.RoleStatus = Number(localroleinfo.localstate);
    statusForm.ContentDesc = ''; // 清空备注
    console.log(statusForm);

    statusDialogVisible.value = true; // 打开对话框
};



// 新建职务设置
const saveAdd = async () => {
    if (!AddFormRef.value) return;
    await AddFormRef.value.validate(async (valid) => {
        if (valid) {
            //调用接口新建职务
            const reponse = await AddRoleZhiW(AddForm);
            if (reponse.data.code == 200) {
                ElMessage.success("编辑职务成功");
                AddDialogVisible.value = false; // 关闭对话框
            } else {
                ElMessage.error("编辑职务失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};

// 编辑职务设置
const saveupdate = async () => {
    if (!updateFormRef.value) return;
    await updateFormRef.value.validate(async (valid) => {
        if (valid) {
            //调用接口编辑职务
            const params = {
                Roleid: UpdateForm.Roleid,
                RoleName: UpdateForm.RoleName,
                DepartmentDescription: UpdateForm.DepartmentDescription
            };
            const reponse = await UpdateRoleZhiW(params);
            if (reponse.data.code == 200) {
                ElMessage.success("编辑职务成功");
                updateDialogVisible.value = false; // 关闭对话框
            } else {
                ElMessage.error("编辑职务失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};


// 保存状态设置
const saveStatus = async () => {
    if (!statusFormRef.value) return;
    await statusFormRef.value.validate(async (valid) => {
        if (valid) {
            console.log('保存状态:', statusForm);
            //调用接口更新角色状态和备注
            const params = {
                RoleId: statusForm.RoleId,
                RoleStatus: statusForm.RoleStatus,
                ContentDesc: statusForm.ContentDesc,
            };
            const reponse = await UpdateRoleStatus(params);
            if (reponse.data.code == 200) {
                ElMessage.success("状态更新成功");
                statusDialogVisible.value = false; // 关闭对话框
            } else {
                ElMessage.error("状态更新失败");
            }


        } else {
            console.log('表单校验失败');
        }
    });
};


// 处理删除
const handleDeleteRole = () => {
    //调用接口删除角色
    ElMessageBox.confirm('确定删除该角色吗?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const reponse = await DeleteRole(localroleinfo.localroleid);
        if (reponse.data.code == 200) {
            ElMessage.success('删除成功');
            router.push('/rolelist')
        } else {
            ElMessage.error('删除失败');
        }
    })
};




// 关闭设置状态对话框时重置表单和校验状态
const resetupdateDialog = () => {
    UpdateForm.Roleid = '';
    UpdateForm.RoleName = '';
    UpdateForm.DepartmentDescription = '';
    if (updateFormRef.value) {
        updateFormRef.value.resetFields();
    }
};


const RoleInfo = reactive<any>({
    roleId: '',
    roleName: '',
})

//返回角色信息列表同时保存设置的权限
const ReturnRole=async()=>{
const response = await SetPermission(localroleinfo.localroleid,PermissionArray)
console.log(localroleinfo.localroleid);

    if(response.data.code==200){
        ElMessage.success('保存成功')
router.push('/rolelist')
    }
    
}

//权限列表
const PermissionList = ref([])

//获取权限列表
const getPermissionList = async () => {
    const res = await GetPermission()
    PermissionList.value = res.data.data
}

// 获取角色权限并反填
const getRolePermissions = async () => {
    const res = await GetPermissionByRoleId(localroleinfo.localroleid)
    if (res.data && res.data.data) {
        res.data.data.forEach((item: any) => {
            PermissionArray.push(item.permissionId)
        })
    }
    console.log(PermissionArray);
    
}

onMounted(() => {
    getPermissionList()
    RoleInfo.roleId = localStorage.getItem('roleId')
    RoleInfo.roleName = localStorage.getItem('roleName')
    // 调用获取角色权限并反填的方法
    getRolePermissions()
})


const activeTab = ref('operation');
</script>

<style scoped>
.permission-list-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 8px;
}

.header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #eee;
}

.avatar {
    margin-right: 20px;
    background-color: #ff6666;
    /* 示例颜色，根据截图调整 */
    color: #fff;
    font-size: 18px;
}

.info {
    flex-grow: 1;
}

.info .title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
}

.info .description {
    font-size: 14px;
    color: #999;
}

.actions .el-button {
    margin-left: 10px;
}

.permission-tabs .el-table {
    margin-top: 10px;
}

/* 调整功能类型列的样式 */
.permission-tabs .el-table .el-table__cell:first-child {
    font-weight: bold;
}
</style>